<template>
  <div class="hacevn">
    <el-button class="cheaback" type="text" icon="el-icon-back" @click="hback"
      >返回</el-button
    >

    <el-tabs title="发布文章">
      <!-- 发布文章的对话框 -->

      <el-form
        :model="pubForm"
        :rules="artkistVisibles"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="案例标题" prop="title">
          <el-input
            v-model="pubForm.title"
            placeholder="请输入标题"
            style="width: 50%"
            maxlength="40"
          ></el-input>
        </el-form-item>
          <el-form-item label="居室" prop="spaceType">
           <el-select v-model="pubForm.spaceType" placeholder="请选择案例居室">
      <el-option label="一居室" value="S1"></el-option>
      <el-option label="二居室" value="S2"></el-option>
      <el-option label="三居室" value="S3"></el-option>
      <el-option label="四居室以上" value="S4"></el-option>
    </el-select>
        </el-form-item>
        <el-form-item label="案例风格" prop="classicCaseType">
           <el-select v-model="pubForm.classicCaseType" placeholder="案例风格">
      <el-option label="北欧极简" value="c1"></el-option>
      <el-option label="现代简约" value="c2"></el-option>
      <el-option label="美式田园" value="c3"></el-option>
      <el-option label="日式" value="c4"></el-option>
      <el-option label="新中式" value="c5"></el-option>
      <el-option label="地中海" value="c6"></el-option>
            <el-option label="奶油风" value="c7"></el-option>
      <el-option label="原木风" value="c8"></el-option>
    </el-select>
        </el-form-item>
         <el-form-item label="面积㎡:" prop="area">
            <el-input
            v-model="pubForm.areaInfo.area"
            placeholder="请输入面积"
            style="width: 17%"
            maxlength="40"
          ></el-input>
  </el-form-item>
        <el-form-item label="选择轮播图">
            <el-upload
          
       action=""
       :http-request="Upload"
       :data="Aliyun"
       :multiple="true"
       :show-file-list="true"
       list-type="picture-card"
       :on-preview="handlePictureCardPreview"
       :on-remove="handleRemove"
       :limit="50"
      >
         <i class="el-icon-plus" />
         </el-upload>
         <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
         </el-dialog>
        </el-form-item>
        <el-form-item label="案例内容" prop="richTextContent">
          <!-- 使用 v-model 进行双向的数据绑定 -->
            <div class="aaa">
         <!-- 工具栏 -->
         <Toolbar
             :editor="editor"
             :defaultConfig="toolbarConfig"
         />
         <!-- 编辑器 -->
         <Editor
             :defaultConfig="editorConfig"
             v-model="html"
             @onChange="onChange"
             @onCreated="onCreated"
         />
     </div>
       
        </el-form-item>

        <el-button class="chonegt" type="primary" @click="hPub()"
          >发布</el-button
        >
      </el-form>
    </el-tabs>
  </div>
</template>

<script>
import {ossmessage,ossuploading } from '@/api/oss'
import { client } from '@/components/Hamburger/ossss'
import { addroutrl } from "@/api/roles";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import ossUpload from '@/components/Hamburger/oss'
export default {
components: { Editor, Toolbar },//组件引入

  data() {
    return {
      dialogVisible:false,
          dialogImageUrl: '',

          Aliyun: {}, // 存签名信息
          progress: 0, // 进度条
          imgUrl: [], // 存上传后的图片url
          toolbarConfig:'',
         IA_inputw:'',
  	 		editor: null, //实例
                 editorConfig: {
               placeholder: '请输入内容...',

      MENU_CONF: {
            uploadImage: {
                customUpload:    //自定义上-oss
                    async (file, insertFn) => {
                        const resultUrl = await ossUpload(file, file.name)
                        insertFn(resultUrl)
                    }
                   }
               }

           },
     html:'',
      file:'',
      category:'',
      resultGTR:'',
       resulted:[],
      listdata:[],
       formdata:{
        companys:[],
        citys:[],
        },
      pubForm: {
        spaceType:'',
        richTextContent:'',
        originalText:'',
        title: "",
        classicCaseType: "",
        text:'',
        areaInfo:{
          area:'',
          unit:'㎡'
        },
        images:[]
      },
      artkistVisibles: {
        title: [
          {
            required: true,
            message: "请输入文章标题",
            trigger: "blur",
          },
          {
            min: 1,
            max: 40,
            message: "文章标题的长度为1-40个字符",
            trigger: "blur",
          },
        ],
        cate_id: [
          {
            required: true,
            message: "请选择文章标题",
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: "请输入文章内容",
            trigger: "blur",
          },
        ],
        cover_img: [
          {
            required: true,
            message: "请选择文章封面",
            trigger: "blur",
          },
        ],
      },
      editorOption: {
	        modules: {
		          toolbar: [
		             ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
					 ['blockquote', 'code-block'], // 引用  代码块
					  [{ header: 1 }, { header: 2 }], // 1、2 级标题
					  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
					  [{ script: 'sub' }, { script: 'super' }], // 上标/下标
					  [{ indent: '-1' }, { indent: '+1' }], // 缩进
					  [{ direction: 'rtl' }], // 文本方向
					  [{ size: ['12px', false, '16px', '18px', '20px', '30px'] }], // 字体大小
					  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
					  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
					  [{ font: [false, 'SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }], // 字体种类
					  [{ align: [] }], // 对齐方式
					  ['clean'], // 清除文本格式
					  ['link', 'image', 'video'] // 链接、图片、视频
              ],
		        placeholder: '请输入正文'
	      	} 
        }
    };
  },
 created() {
  this.getAliyun()

 },
  methods: {
         async getAliyun() {
          const { data } = await ossmessage({
        'ossGroup':'CommodityMainImages'
      })
          this.Aliyun = data
          // console.log(this.Aliyun);
          },
          // 富文本上传图片
      onCreated(editor) {
   			            this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
   			        },
                // 富文本截取文字
   			        onChange(editor) {
   			            // console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
                     this.cofg = editor.getHtml()
                    this.IA_inputw = this.cofg.replace(/<[^<>]+>/g,"").replace(
                 /&nbsp;/gi,
                 ""
                  );
                  //  console.log("富文本编辑器输出内容为：" + this.cofg);
                  //  console.log("==========================================");
                   console.log("富文本编辑器转换后输出文本为：" + this.IA_inputw.slice(0,5));
   			        },

        // 上传图片
  Upload(file) {
   const that = this
   // 判断扩展名
   const tmpcnt = file.file.name.lastIndexOf('.')
   const exname = file.file.name.substring(tmpcnt + 1)
   const names = ['jpg', 'jpeg', 'png','webP']
   if (names.indexOf(exname) < 0) {
    this.$message.error('不支持的格式!')
    return
   }
   if (file.size > 1024 * 1024) {
    this.$message.error('图片大小最大1M')
    return
   }
  
   async function multipartUpload() {
    const listdata = await ossuploading({
      'fileName':'.jpg','ossGroup':'CommodityMainImages'
    })
     let fileName = listdata.data.path
    //  console.log('741',fileName);
    //  console.log('999',file);
    client(that.Aliyun).put(fileName, file.file,
     {
      progress: function(p) { // 获取进度条的值
      //  console.log('777',p)
       that.progress = p * 100
      }
     }).then(
     result => {
      // 下面是如果对返回结果再进行处理，根据项目需要
      // console.log(result)
      // that.imgUrl = 'http://' + result.bucket + '.' + that.Aliyun.endpoint + '/' + result.name
      that.dialogImageUrl = result.url
        // console.log('444',that.dialogImageUrl)
      that.imgUrl.push({
       name: file.file.name,
       url: result.url
      })

     })
   }
   multipartUpload()
  },
  // 图片预览
  handlePictureCardPreview(file) {
   this.dialogImageUrl = file.url
   this.dialogVisible = true
  },
  // 删除图片
  handleRemove(file, fileList) {
   // console.log(file)
   for (var i in this.imgUrl) {
    if (this.imgUrl[i].name === file.name) {
     this.imgUrl.splice(i, 1)
    }
   }
  //  console.log(this.imgUrl);
  },
    // 发布
    async hPub() {
      this.pubForm.richTextContent = this.html
        for (let i = 0; i < this.imgUrl.length; i++) {
          this.pubForm.images.push(this.imgUrl[i].url)
        }
       setTimeout(async() => {
       
         this.pubForm.originalText = this.IA_inputw.slice(0,40)
     
      // console.log('741',this.pubForm.images);
         this.html = this.html.replace(/<img/gi,
          '<img style="max-width:100%; height:auto"')
          // // console.log('777',this.html);
      this.$refs.pubFormRef.validate(async (valid) => {
        if(!valid) return
      
      this.pubForm.text = `<html lang="en"><head> <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" >
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
   <title>${this.pubForm.title}</title>
 <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">

   <style>
     .box {
      position: relative;
      width: 100%;
      height: 300px;

      margin: 0 auto;
    }
  
    html,
    body {
      position: relative;
      height: 100%;
    }

    body {
      background: #fff;
      font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
      font-size: 14px;
      color: #000;
      margin: 0;
      padding: 0;
    }
 .swiper-horizontal>.swiper-pagination-bullets, .swiper-pagination-bullets.swiper-pagination-horizontal, .swiper-pagination-custom, .swiper-pagination-fraction{
      bottom: 85px !important;
      background-color: rgba(0,0,0,0.5);
      width: 50px;
      border-radius: 20px;
      color: #eee;
      margin-left: 80%;
      height:20px;
      line-height:20px;
    }

    .swiper {
      overflow: hidden;
      width: 100%;
      height: 100%;
    }

   </style>
   </head>
    <body>
      
<div class="box">
    <!-- Swiper -->
    <div class="swiper mySwiper">
      <div class="swiper-wrapper">
      ${this.pubForm.images.map(item=>(`<div class="swiper-slide"><img style="width:100%;height:80%;" src=${item}></img></div>`)).join('')}
      </div>
      <div class="swiper-pagination"></div>
    </div>

  

    <div style="background-color:#fff; height:70%;padding:1px 10px 10px 10px;
    border-radius:18px 18px 0 0;position: relative; bottom: 77px;z-index:999">${this.html}</div>
      <div class="blackScreen" style="display: none;display:none;    position:fixed;    top:0;    right:0;    bottom:0;    left:0;    background-color:#000000;    z-index:1000;">"
            <span class="fullScreenImg" style='position:absolute;    top:0;    right:0;    bottom:60px;    left:0;    background:center center no-repeat;    background-size:contain;'></span>" 
        </div>

  <script src="https://code.jquery.com/jquery-3.4.1.min.js"><\/script>
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"><\/script>
     <script>
    //  轮播图
      var swiper = new Swiper(".mySwiper", {
        loop: true,
        autoplay: {
        delay: 1000,//1秒切换一次
        disableOnInteraction: false,  // 鼠标点击 触摸之后，自动继续播放
      },
      pagination: {
        el: ".swiper-pagination",
        type: 'fraction'
      },
    });
    
    $(document).ready(function () {
    $("body").append("" );
});
 
$(function () {
  
// 放大图片 

    $('img').on('click', function () {
        // console.log("放大");
        if (this.getAttribute("src")) {
             $(".fullScreenImg").css('background-image', 'url(\\\'' + this.getAttribute('src') + '\\\')');
            $(".blackScreen").fadeIn(100);
        }
    });
  
// 关闭放大图片
    $(".blackScreen").on("click", function () {
        // console.log("关闭");
        $(".blackScreen").fadeOut(100);
    });
 
});
    <\/script>
    
 
    </body>
      
    </html>`
      const res = await addroutrl(this.pubForm); 
      this.$message.success(res.msg)
      if(res.code == 200){
        this.$router.push('/home/fitments/classic')
     
      } else return
      })
      // console.log(res);
       },1000)
    },

 


    // wangeditor临时

    hback() {
      this.$router.back();
    },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

<style scoped>
.el-form{
  line-height: 160px;
}
.hacevn {
  background-color: #fff;
  padding: 20px;
}
.chonegt {
  transform: translateX(140%);
  color: #fff;
  background-color: #ff7144;
  border: 1px solid #fff;
}
.escanut {
  width: 70%;
  height: 70%;
}

.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options {
  border-color: #ccc;
  height: 125px;


}

.aaa{
  width: 80%;
}
</style>

